<template>
    <div class="update_form">
        <a-form :model="productInfo"
                @finish="onFinish"
                autocomplete="off"
                name="basic"
        >
            <a-form-item
                    name="name"
                    label="商品名称"
                    :rules="[{ required: true, message: '请输入商品名称' }]"
                    has-feedback>
                <a-input size="large" v-model:value="productInfo.name"/>
            </a-form-item>

            <a-form-item
                    name="productCode"
                    label="商品编号"
                    has-feedback>
                <a-input size="large" v-model:value="productInfo.productCode"/>
            </a-form-item>

            <a-form-item
                    name="typeId"
                    label="商品类别"
                    has-feedback>
                <a-select
                        style="width: 300px;"
                        v-model:value="productInfo.typeId"
                        @change="selectProductType"
                >
                    <a-select-option v-for="p in typeList" :key="p.id" :value="p.id">
                        {{p.name}}
                    </a-select-option>
                </a-select>
            </a-form-item>

            <a-form-item
                    name="price"
                    label="商品价格"
                    :rules="[{ required: true, message: '请输入商品价格' }]">
                <a-input size="large" v-model:value="productInfo.price"/>
            </a-form-item>

            <a-form-item
                    name="imagePath"
                    label="商品图片"
                    style="width: 60%">
                <a-upload
                        v-if="productInfo.imagePath==='' || productInfo.imagePath==null"
                        v-model:value="productInfo.imagePath"
                        :before-upload="beforeUpload"
                        :custom-request="upLoadImage"
                >
                    <a-button>
                        <upload-outlined/>
                        上传图片
                    </a-button>
                </a-upload>
                <div v-else>
                    <img style="height: 60%;width: 100%;margin-bottom: 20px;display: block" :src="productInfo.imagePath"
                         alt="尚未上传图片"/>
                    <a-button block size="small" @click="deleteImage">
                        <delete-outlined/>
                        删除图片
                    </a-button>
                </div>
            </a-form-item>

            <a-form-item
                    name="detail"
                    label="商品详细介绍">
                <a-textarea v-model:value="productInfo.detail" :rows="6" placeholder="请输入商品详细介绍" :maxlength="80"/>
            </a-form-item>

            <a-form-item>
                <a-button style="width: 100%" size="large" html-type="submit" type="primary">提交</a-button>
            </a-form-item>
        </a-form>
    </div>
</template>

<script>
    import {request} from "@/utils/request";
    import api from "@/constants/api";
    import {message} from "ant-design-vue";
    import {compass} from "@/utils/compass";

    export default {
        name: "UpdateDishPage",
        data() {
            return {
                productId: '',
                productInfo: {},
                typeList: [],
                //options: [],
            }
        },
        mounted() {
            const productId = this.$route.query.id;
            this.productId = productId;
            this.getProductInfo(productId);
            this.getProductTypeList();
        },
        methods: {
            getProductInfo(id) {
                const data = new FormData();
                data.append("id", id);
                request({
                    url: api.GET_PRODUCT_INFO_BY_ID,
                    data: data,
                    method: "POST"
                }).then(res => {
                    this.productInfo = res;
                })
            },

            getProductTypeName(id) {
                let name = "";
                this.typeList.forEach(item => {
                    if (item.id === id) {
                        name = item.name;
                    }
                })
                return name;
            },

            selectProductType(value) {
                this.productInfo.typeId = value
            },

            beforeUpload(file) {
                const isJPG = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png' || file.type === 'image/bmp'
                if (!isJPG) {
                    message.error('请上传图片文件');
                }
                const isLt2M = file.size / 1024 < 1024 * 200 && file.size / 1024 > 10;
                if (!isLt2M) {
                    message.error('文件大小应在10KB~200KB之间');
                }
                return isJPG && isLt2M
            },

            upLoadImage(file) {
                let that = this;
                that.getBase64(file).then(res => {
                    console.log(res.length);
                    compass(res, 512 * 256, 1).then(r => {
                        console.log('压缩后：' + r.length);
                        that.productInfo.imagePath = r;
                    })
                })
            },

            getBase64(file) {
                return new Promise(function (resolve, reject) {
                    let reader = new FileReader();
                    let imgResult = "";
                    reader.readAsDataURL(file.file);
                    reader.onload = function () {
                        imgResult = reader.result;
                    };
                    reader.onerror = function (error) {
                        reject(error);
                    };
                    reader.onloadend = function () {
                        resolve(imgResult);
                    };
                });
            },
            onFinish(values) {
                const data = new FormData();
                data.append("id", this.productId);
                data.append("productCode", values.productCode);
                data.append("name", values.name);
                data.append("typeId", values.typeId);
                data.append("type", this.getProductTypeName(values.typeId));
                data.append("price", values.price);
                data.append("imagePath", values.imagePath);
                data.append("detail", values.detail);
                request({
                    url: api.UPDATE_PRODUCT,
                    method: "POST",
                    data: data,
                    pureData: false,
                }).then(res => {
                    if (res.code === 200) {
                        message.success(res.message)
                        this.$router.push({name: "DishPage"});
                    } else {
                        message.error(res.message)
                    }
                })
            },


            deleteImage() {
                this.productInfo.imagePath = '';
            },

            getProductTypeList() {
                request({
                    url: api.GET_PRODUCT_TYPE_LIST,
                    method: "GET",
                }).then(res => {
                    this.typeList = res;
                })
            },
        },
    }
</script>

<style scoped>

    .update_form {
        display: flex;
        flex-direction: column;
        padding: 20px 0 0 80px;
        width: 500px;
    }
</style>